using AdminSG3L.Applicaticn.Dtos;
using AdminSG3L.Applicaticn.Commands;
using AdminSG3L.Applicaticn.ServicesInterface;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System.Text;
using System.Text.Json;

namespace AdminSG3L.Applicaticn.Services;

/// <summary>
/// Gitee文件上传服务
/// </summary>
public class GiteeFileUploadService : IFileUploadService
{
    private readonly IConfiguration _configuration;
    private readonly string _giteeToken;
    private readonly string _giteeRepo;
    private readonly string _giteeOwner;

    public GiteeFileUploadService(IConfiguration configuration)
    {
        _configuration = configuration;
        _giteeToken = _configuration["Gitee:AccessToken"] ?? throw new InvalidOperationException("Gitee AccessToken未配置");
        _giteeRepo = _configuration["Gitee:Repository"] ?? throw new InvalidOperationException("Gitee Repository未配置");
        _giteeOwner = _configuration["Gitee:Owner"] ?? throw new InvalidOperationException("Gitee Owner未配置");
    }

    public async Task<ApiResponse<string>> UploadFileAsync(IFormFile file, string folder)
    {
        try
        {
            if (file == null || file.Length == 0)
                return ApiResponse<string>.Fail("文件不能为空");

            // 验证文件类型
            var allowedTypes = new[] { "image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp" };
            if (!allowedTypes.Contains(file.ContentType.ToLower()))
                return ApiResponse<string>.Fail("只支持图片文件 (jpg, png, gif, webp)");

            // 验证文件大小 (5MB)
            if (file.Length > 5 * 1024 * 1024)
                return ApiResponse<string>.Fail("文件大小不能超过5MB");

            // 生成文件名
            var extension = Path.GetExtension(file.FileName);
            var fileName = $"{Guid.NewGuid()}{extension}";
            var filePath = $"{folder}/{fileName}";

            // 读取文件内容并转换为Base64
            byte[] fileBytes;
            using (var memoryStream = new MemoryStream())
            {
                await file.CopyToAsync(memoryStream);
                fileBytes = memoryStream.ToArray();
            }
            var base64Content = Convert.ToBase64String(fileBytes);

            // 构建Gitee API请求
            var requestData = new
            {
                message = $"Upload {fileName}",
                content = base64Content
            };

            var json = JsonSerializer.Serialize(requestData);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            using var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Authorization", $"token {_giteeToken}");

            var apiUrl = $"https://gitee.com/api/v5/repos/{_giteeOwner}/{_giteeRepo}/contents/{filePath}";
            var response = await httpClient.PostAsync(apiUrl, content);

            if (response.IsSuccessStatusCode)
            {
                var responseJson = await response.Content.ReadAsStringAsync();
                var responseData = JsonSerializer.Deserialize<JsonElement>(responseJson);
                
                if (responseData.TryGetProperty("content", out var contentElement) &&
                    contentElement.TryGetProperty("download_url", out var downloadUrlElement))
                {
                    var downloadUrl = downloadUrlElement.GetString();
                    return ApiResponse<string>.Success(downloadUrl, "文件上传成功");
                }
                
                return ApiResponse<string>.Fail("上传成功但无法获取文件URL");
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                return ApiResponse<string>.Fail($"上传失败: {response.StatusCode} - {errorContent}");
            }
        }
        catch (Exception ex)
        {
            return ApiResponse<string>.Fail($"上传文件时发生错误: {ex.Message}");
        }
    }
}